import mqtt from "mqtt";

class MqttClient {
  private client: mqtt.MqttClient | null = null;

  // // 消息记录
  // private messageLog: Record<string, boolean> = {};

  // 获取连接状态
  public getConnectionStatus(): boolean {
    return !!this.client && this.client.connected;
  }

  // 连接到 MQTT Broker
  public connect(): Promise<void> {
    return new Promise((resolve, reject) => {
      if (this.client) {
        console.log("Already connected to MQTT broker.");
        resolve();
        return;
      }
      const brokerUrl = import.meta.env.VITE_APP_MQTT_BROKER_URL;
      if (!brokerUrl) {
        reject(new Error("MQTT broker URL is not defined."));
        return;
      }
      const options: mqtt.IClientOptions = {
        clientId: `ts_mqtt_client_${Date.now()}`,
        path: "/mqtt",
        username: import.meta.env.VITE_APP_MQTT_USERNAME,
        password: import.meta.env.VITE_APP_MQTT_PASSWORD,
        port: parseInt(import.meta.env.VITE_APP_MQTT_PORT || "8083"),
      };

      this.client = mqtt.connect(brokerUrl, options);

      this.client.on("connect", () => {
        console.log("Connected to MQTT broker.");
        resolve();
      });

      this.client.on("error", (err) => {
        console.error("MQTT connection error:", err);
        reject(err);
      });
    });
  }

  // 订阅主题
  public subscribe(topic: string | string[]): Promise<void> {
    return new Promise((resolve, reject) => {
      if (!this.client) {
        reject(new Error("Not connected to MQTT broker."));
        return;
      }

      this.client.subscribe(topic, (err) => {
        if (err) {
          console.error("Failed to subscribe to topic:", err);
          reject(err);
        } else {
          console.log(`Subscribed to topic: ${topic}`);
          resolve();
        }
      });
    });
  }

  // 取消订阅
  public unsubscribe(topic: string | string[]): Promise<void> {
    return new Promise((resolve, reject) => {
      if (!this.client) {
        reject(new Error("Not connected to MQTT broker."));
        return;
      }

      this.client.unsubscribe(topic, (err) => {
        if (err) {
          console.error("Failed to unsubscribe from topic:", err);
        }
      });
    });
  }

  // 发布消息
  public publish(topic: string, message: string): Promise<void> {
    return new Promise((resolve, reject) => {
      if (!this.client) {
        reject(new Error("Not connected to MQTT broker."));
        return;
      }

      this.client.publish(topic, message, (err) => {
        if (err) {
          console.error("Failed to publish message:", err);
          reject(err);
        } else {
          console.log(`Published message to topic "${topic}": ${message}`);
          resolve();
        }
      });
    });
  }

  // 断开连接
  public disconnect(): void {
    if (this.client) {
      this.client.end();
      this.client = null;
      console.log("Disconnected from MQTT broker.");
    }
  }

  // 监听消息
  public onMessage(callback: (topic: string, message: Buffer) => void): void {
    if (!this.client) {
      console.warn("Not connected to MQTT broker.");
      return;
    }

    this.client.on("message", (topic, message) => {
      // const messageId = message.toString("hex"); // 使用消息的十六进制表示作为唯一标识
      // if (this.messageLog[messageId]) {
      //   console.log("Duplicate message received, ignoring.");
      //   return;
      // }
      // this.messageLog[messageId] = true;
      callback(topic, message);
    });
  }
}

export default MqttClient;
